package com.nefu.huiyi.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nefu.huiyi.entity.City;
import com.nefu.huiyi.result.HttpResult;
import com.nefu.huiyi.service.CityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/cities")
@Tag(name = "城市管理接口")
public class CityController {

    @Autowired
    private CityService cityService;

    @PostMapping("/new")
    @Operation(summary = "新增城市")
    public HttpResult<City> saveCity(@RequestBody City city) {
        City savedCity = cityService.saveCity(city);
        return HttpResult.success(savedCity);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除城市")
    public HttpResult<Boolean> deleteCity(@PathVariable Integer id) {
        boolean result = cityService.deleteCity(id);
        return result ? HttpResult.success(true) : HttpResult.failed("删除失败");
    }

    @PutMapping
    @Operation(summary = "更新城市信息")
    public HttpResult<City> updateCity(@RequestBody City city) {
        City updatedCity = cityService.updateCity(city);
        return HttpResult.success(updatedCity);
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询城市")
    public HttpResult<City> getCityById(@PathVariable Integer id) {
        City city = cityService.getCityById(id);
        return HttpResult.success(city);
    }

    @GetMapping("/all")
    @Operation(summary = "获取所有城市")
    public HttpResult<List<City>> findAll() {
        List<City> cities = cityService.findAll();
        return HttpResult.success(cities);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询城市列表")
    public HttpResult<IPage<City>> getCityPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String cityName,
            @RequestParam(required = false) String province) {

        Page<City> page = new Page<>(pageNum, pageSize);
        IPage<City> cityPage = cityService.getCityPage(page, cityName, province);
        return HttpResult.success(cityPage);
    }

    @GetMapping("/pharma")
    @Operation(summary = "按医药公司数量筛选城市")
    public HttpResult<List<City>> getCitiesByPharmaCount(
            @RequestParam(defaultValue = "0") Integer minCount) {

        List<City> cities = cityService.getCitiesByPharmaCount(minCount);
        return HttpResult.success(cities);
    }
}